<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of CampaignsController
 *
 * @author Admin
 */
class Adv_CampaignsController extends Zend_Controller_Action
{
    public function init() 
    {
        $this->_helper->layout->setLayout('advertiser');        
    }   
    
    public function indexAction() {
        
    }
    
    public function newcampaignfirstAction() {
        $campaigns = new Adv_Model_Campaigns();
        $allCategories = $campaigns->getAllCategories();
        $this->view->allCategories = $allCategories;
        
        $allCountries = $campaigns->getAllCountries();        
        $array = Array();        
        foreach ($allCountries as $key => $country) {
            $array = $campaigns->getAllRegionsCountry($country['id']);
            $allCountries[$key]['regions'] = $array;
        }        
        $this->view->allCountries = $allCountries;
    }
    
    public function newcampaignsecondAction() {
        
    }
    /**
     * Формируем список всех рекламных компаний 
     */
    public function campaignsAction() {
        $obj = new Adv_Model_Campaigns();
        $id_adv = Zend_Auth::getInstance()->getIdentity()->id;
        $campaigns = $obj->getAllCampaigns($id_adv);

        $this->view->campaigns = $campaigns;
    }
    
    public function activatecampaignAction() {
        $obj = new Adv_Model_Campaigns();
        $id = $this->_getParam('id');
        $id_adv = Zend_Auth::getInstance()->getInstance()->id;
        $data = array (
            'id_status' => 1
        );
        $obj->activateDeactivateCampaign($id, $data, $id_adv);
        $this->_helper->redirector('campaigns', 'campaigns');
    }
    
    public function deactivatecampaignAction() {
        $obj = new Adv_Model_Campaigns();
        $id = $this->_getParam('id');
        $id_adv = Zend_Auth::getInstance()->getInstance()->id;
        $data = array (
            'id_status' => 3
        );
        $obj->activateDeactivateCampaign($id, $data, $id_adv);
        $this->_helper->redirector('campaigns', 'campaigns');
    }
    
    public function deletecampaignAction() {
        $obj = new Adv_Model_Campaigns();
        $id = $this->_getParam('id');
        $obj->deleteCampaign($id);
        $this->_helper->redirector('campaigns', 'campaigns');
    }
    
    public function addcampaignfirstAction() {
        $campaigns = new Adv_Model_Campaigns();
        $publisher = new Pub_Model_Publisher();
        $idAdvertiser = Zend_Auth::getInstance()->getIdentity()->id;
        $validate = new Zend_Filter();
        $validate->addFilter(new Zend_Filter_StringTrim())
                 ->addFilter(new Zend_Filter_StripTags());
        
        
        if ($this->getRequest()->isPost()) {
            $post = $this->getRequest()->getPost(); 
            
            /**
             * Создание рекламной кампании
             */
            $dataCampaign = array(
                'id_advertiser' => $idAdvertiser,                
                'id_category'   => $validate->filter($post['category_adv']),
                'id_status'     => 2,
                'name'          => $validate->filter($post['company_name']),
                'url_site'      => $validate->filter($post['site_url']),
                'license'       => $validate->filter($post['license']),
                'date_start'    => $validate->filter(strtotime($post['date_start'])),
                'date_end'      => $validate->filter(strtotime($post['date_end']))
            );            
            $idCampaign = $campaigns->addCampaign($dataCampaign);
            $idCampaign = 1;
            //запись стран показа кампании
            if (isset($post['geography_countries'])) {
                $count = count($post['geography_countries']);                
                for ($i = 0; $i < $count; $i++) {
                    $dataCountries = array(
                        'id_campaign' => $idCampaign,
                        'id_country'  => $validate->filter($post['geography_countries'][$i])
                    );                     
                    $campaigns->addGeographySpaceCountry($dataCountries);                     
                }                     
            }       
            //запись регионов показа кампании
            if (isset($post['geography_regions'])) {
                $count = count($post['geography_regions']);
                for ($i = 0; $i < $count; $i++) {
                    $dataRegions = array(
                        'id_campaign' => $idCampaign,
                        'id_region'   => $validate->filter($post['geography_regions'][$i])
                    );
                    $campaigns->addGeographySpaceRegion($dataRegions);                    
                }
            }
            //запись бюджета кампании
            $budget = $campaigns->jsMoneyStrToFloat($post['budget']);
            $weekBudget = $campaigns->jsMoneyStrToFloat($post['week_budget']);
            $dayBudget = $campaigns->jsMoneyStrToFloat($post['day_budget']);
            $dataBudget = array(
                'id_campaign'  => $idCampaign,
                'start_budget' => $validate->filter($budget),
                'week_budget'  => $validate->filter($weekBudget),
                'day_budget'   => $validate->filter($dayBudget)
            );            
            $campaigns->addCampaignBudget($dataBudget);
            //запись контактной информации
            if ($post['city'] != null) {
                $dataContact = array(
                    'id_campaign'    => $idCampaign,
                    'country'        => $validate->filter($post['country_contact']),
                    'city'           => $validate->filter($post['city']),
                    'address'        => $validate->filter($post['address']),
                    'work_time'      => $validate->filter($post['work_time']),
                    'telephone'      => $validate->filter($post['telephone']),
                    'email'          => $validate->filter($post['email']),
                    'company'        => $validate->filter($post['company']),
                    'contact_person' => $validate->filter($post['contact_person']) 
                );                
                $campaigns->addContactsCampaign($dataContact);
                if ($post['create_mini_site'] == 'on') {
                    //create mini stie
                }
            }
            
            /**
             * Создание контекстной рекламы
             */
            if (isset($post['name_ad'])) {
                $dataAd = array(
                    'name'       => $validate->filter($post['name_ad']),
                    'date_start' => $validate->filter(strtotime($post['date_start_ad'])),
                    'date_end'   => $validate->filter(strtotime($post['date_end_ad'])),
                    'header'     => $validate->filter($post['header_ad']),
                    'text'       => $validate->filter($post['text_ad'])
                ); 
                $idContext = $campaigns->addContextAdver($dataAd);                
                $idContext = 1;
                //запись бюджета кампании
                $dataContextBudget = array(
                    'id_context'   => $idContext,
                    'start_budget' => $validate->filter($campaigns->jsMoneyStrToFloat($post['budget_ad'])),
                    'week_budget'  => $validate->filter($campaigns->jsMoneyStrToFloat($post['week_budget_ad'])),
                    'day_budget'   => $validate->filter($campaigns->jsMoneyStrToFloat($post['day_budget_ad']))
                );
                $campaigns->addContextBudget($dataContextBudget);
                
                //запись ключевых слов кампании
                $keywordsAd = explode(',', $validate->filter($post['keywords_ad']));                
                foreach ($keywordsAd as $keyAd) {                    
                    $key = ltrim(rtrim($keyAd));                    
                    $oldKeys = $publisher->getSimilarKeywords($key);                    
                    //если введденые кейворды уже сущестуют
                    if (!empty($oldKeys)) {
                        foreach ($oldKeys as $oldKey) {
                            $dataConnectionKey = array(
                                'id_keyword' => $oldKey['id'],
                                'id_context' => $idContext
                            ); 
                            //просто связываем кейворд с контекстной рекламой
                            $campaigns->setContextAndKeywordConnection($dataConnectionKey);
                        }
                    } else {
                        $dataNewKeyword = array(
                            'id_bid' => 1,
                            'name'   => $key
                        );
                        //если кейвордов в базе не найдено, создаем новые
                        $idKeyword = $campaigns->addNewKeyword($dataNewKeyword);
                        $idKeyword = 1;
                        $dataConnectionNewKey = array(
                            'id_context' => $idContext,
                            'id_keyword' => $idKeyword
                        );
                        //и связываем их с рекламой
                        $campaigns->setContextAndKeywordConnection($dataConnectionNewKey);
                    }
                }                
            }
            
            /**
             * Создание микроблога или соц.сети
             */
            if ($post['name_adver_social'] != null) {
                $dataSocial = array(
                    'name'        => $validate->filter($post['name_adver_social']),
                    'cost'        => $validate->filter($post['cost_adver_social']),
                    'description' => $validate->filter($post['description_social']),
                    'date_start'  => $validate->filter(strtotime($post['date_start_social'])),
                    'date_end'    => $validate->filter(strtotime($post['date_end_social']))
                );
                $campaigns->addBlogOrSocialAdver($dataSocial);
            }
            
            /**
             * Создание баннерной рекламы
             */
            if ($post['name_banner'] != null) {                
                //обработка и загрузка картинки
                $upload = new Zend_File_Transfer();          
                $upload->addValidator('Extension', false, array('jpg', 'png'. 'gif'));
                $file = $upload->getFileInfo();
                $ext = pathinfo($file['image_file']['name'], PATHINFO_EXTENSION);                
                $imageName = rand().".".$ext;                                
                $upload->addFilter('Rename', realpath(dirname('.')).
                DIRECTORY_SEPARATOR.
                'banners'.
                DIRECTORY_SEPARATOR.
                $imageName);
                $upload->receive();
                
                //запись данных баннера
                $dataBanner = array(
                    'name'       => $validate->filter($post['name_banner']),
                    'image'      => $imageName,
                    'date_start' => $validate->filter(strtotime($post['date_start_banner'])),
                    'date_end'   => $validate->filter(strtotime($post['date_end_banner']))
                );
                $idBanner = $campaigns->addBannerAdver($dataBanner);                
                //запись бюджета баннера
                $dataBudgetBanner = array(
                    'id_banner'    => $idBanner,
                    'start_budget' => $validate->filter($campaigns->jsMoneyStrToFloat($post['budget_banner'])),
                    'week_budget'  => $validate->filter($campaigns->jsMoneyStrToFloat($post['week_budget_banner'])),
                    'day_budget'   => $validate->filter($campaigns->jsMoneyStrToFloat($post['day_budget_banner']))
                );
                $campaigns->addBannerBudget($dataBudgetBanner);
                
                //запись ключевых слов кампании
                $keywordsBanner = explode(',', $validate->filter($post['keywords_banner']));                 
                foreach ($keywordsBanner as $keyBanner) {                    
                    $key = ltrim(rtrim($keyBanner));                    
                    $oldKeys = $publisher->getSimilarKeywords($key);                    
                    //если введденые кейворды уже сущестуют
                    if (!empty($oldKeys)) {
                        foreach ($oldKeys as $oldKey) {
                            $dataConnectionKey = array(
                                'id_keyword' => $oldKey['id'],
                                'id_banner' => $idBanner
                            ); 
                            //просто связываем кейворд с контекстной рекламой
                            $campaigns->setBannerAndKeywordConnection($dataConnectionKey);
                        }
                    } else {
                        $dataNewKeyword = array(
                            'id_bid' => 1,
                            'name'   => $key
                        );
                        //если кейвордов в базе не найдено, создаем новые
                        $idKeyword = $campaigns->addNewKeyword($dataNewKeyword);                        
                        $dataConnectionNewKey = array(
                            'id_banner' => $idContext,
                            'id_keyword' => $idKeyword
                        );
                        //и связываем их с рекламой
                        $campaigns->setBannerAndKeywordConnection($dataConnectionNewKey);
                    }
                }
            }            
            $this->_helper->redirector('newcampaignsecond', 'campaigns');
        }
    }
}

?>
